#include <iostream>
#include <unordered_map>
#include <functional>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPContentHeader.h>
#include <cgicc/CgiEnvironment.h>
#include "database_handler/media_control.hh"
using namespace leyi_media::media_control;
using namespace cgicc;
using namespace std;

int main()
{
    std::cout << "Content-Type: application/json; charset=utf-8"
              << "\r\n\r\n";
    try
    {
        Cgicc cc;
        string method, id, word, ret;
        auto it = cc.getElement("method");
        if (it != cc.getElements().end())
            method = it->getStrippedValue();
        it = cc.getElement("id");
        if (it != cc.getElements().end())
            id = it->getStrippedValue();
        it = cc.getElement("word");
        if (it != cc.getElements().end())
            word = it->getStrippedValue();
        Json::Value root;
        string result;
        auto &media_controler = media_controler_t::get_instance();
        unordered_map<string, function<void()>> func_map{
            {"search_all", [&]()
             { media_controler.select_all(root); }},
            {"search_one", [&]()
             { media_controler.select_one(id, root); }},
            {"search_like", [&]()
             { media_controler.select_like(word, root); }},
            {"get_comments", [&]()
             { media_controler.get_comments(id, root); }}};
        if (func_map.find(method) != func_map.end())
        {
            func_map[method]();
        }
        json_util::Serialize(root, ret);
        std::cout << ret;
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << "line: " << __LINE__ << '\n';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}